package com.pagoda.nerp.trade.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.pagoda.nerp.trade.app.quality.utils.InvokeQualityPartUtils;
import com.pagoda.nerp.trade.common.BaseResult;
import com.pagoda.nerp.trade.common.ConstantDefine;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.common.exception.NORecordInDBException;
import com.pagoda.nerp.trade.common.exception.QualityException;
import com.pagoda.nerp.trade.common.objectutil.PropertyConfigurer;
import com.pagoda.nerp.trade.dao.*;
import com.pagoda.nerp.trade.entity.*;
import com.pagoda.nerp.trade.service.QualityService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * Created by ww on 2016/12/16.
 */
@Service
public class QualityServiceImpl implements QualityService {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MdQualityRecordDao qualityRecordDao;
    @Autowired
    private SysBillRuleDao sysBillRuleDao;
    @Autowired
    private MdVendorDao vendorDao;
    @Autowired
    private MdVendorGoodsDao vendorGoodsDao;
    @Autowired
    private MdAccountDao accountDao;
    @Autowired
    private MdGoodsDao goodsDao;
    @Autowired
    private MdFeedbackDao feedbackDao;

    @Override
    @Transactional
    public int applyQualityTest(MdQualityRecord qualityRecord, Object pics) throws Exception {

        //获取Id
        int qualityRecordId = sysBillRuleDao.generateId("QUALITY_RECORD_ID");
        if (qualityRecordId == 0) {
            logger.error("Failed to get qualityRecordId!");
            throw new RuntimeException("Failed to get QUALITY_RECORD_ID");
        }
        qualityRecord.setQualityRecordId(qualityRecordId);

        //获取code
        String qualityRecordCode = sysBillRuleDao.generateCode("QUALITY_RECORD_NO");
        if (qualityRecordCode == null) {
            logger.error("Failed to get QUALITY_RECORD_NO");
            throw new RuntimeException("Failed to get QUALITY_RECORD_NO");
        }
        qualityRecord.setQualityRecordNo(qualityRecordCode);
        qualityRecord.setQualityPlatId(qualityRecordCode);

        MdAccount account = accountDao.selectByPrimaryKey(qualityRecord.getMdAccountId());
        if (account == null) {
            logger.debug("The account is not exist,accountId=" + qualityRecord.getMdAccountId());
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_ACCOUNT_NOT_EXIST);
        }

        //查询供应商是否存在
        MdVendor vendor = vendorDao.selectByPrimaryKey(qualityRecord.getVendorId());
        if (vendor == null) {
            logger.debug("The vendor is not exist,vendorID=" + qualityRecord.getVendorId());
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_VENDOR);
        }

        //查询商品是否存在
        MdGoods goods = goodsDao.selectByPrimaryKey(qualityRecord.getGoodsId());
        if (goods == null) {
            logger.debug("The vendor's goods is not exist,vendorID=" + qualityRecord.getVendorId() + ",vendorGoodsId" + qualityRecord.getVendorGoodsId());
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_GOODS);
        }

        if (qualityRecord.getVendorGoodsId() > 0) {
            //查询供应商水果是否存在
            MdVendorGoods vendorGoods = vendorGoodsDao.selectByPrimaryKey(qualityRecord.getVendorGoodsId());
            if (vendorGoods == null) {
                logger.error("The vendor's goods is not exist,vendorID=" + qualityRecord.getVendorId() + ",vendorGoodsId" + qualityRecord.getVendorGoodsId());
                throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_GOODS);
            }
            if ((int) vendorGoods.getGoodsId() != goods.getGoodsId()) {
                logger.error("The goodsId is not match with vendorGoodsId!");
                throw new QualityException(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
            }
            if ((int) vendorGoods.getVendorId() != qualityRecord.getVendorId()) {
                logger.error("The vendorId is  match with vendorGoodsId!");
                throw new QualityException(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
            }

        }

        //调用远程接口参数
        Map<String, Object> param_json = new HashMap<String, Object>();
        param_json.put("code", qualityRecordCode);
        param_json.put("customer_account", account.getAccount());
        param_json.put("customer_name", account.getName());
        param_json.put("category_id", goods.getCategoryId());
        param_json.put("goods_code", goods.getGoodsCode());
        param_json.put("goods_name", goods.getGoodsName());
        param_json.put("supplier_code", vendor.getVendorCode());
        param_json.put("supplier_name", vendor.getVendorName());
        param_json.put("supplier_tel", vendor.getPhoneNumber());
        param_json.put("origin", qualityRecord.getArea());
        param_json.put("origin_price", qualityRecord.getPrice());
        param_json.put("output", qualityRecord.getYield());
        param_json.put("scale", qualityRecord.getScale());
        param_json.put("qc_type", qualityRecord.getQtyType().equals("A") ? 1 : 2);
        param_json.put("origin_place", qualityRecord.getAddress());
        param_json.put("origin_contact", qualityRecord.getContacts());
        param_json.put("origin_contact_tel", qualityRecord.getPhoneNumber());
        param_json.put("pics", pics == null ? null : (String) pics == null);


        //调用质检平台接口：创建质检单
        JSONObject jsResp = InvokeQualityPartUtils.invokeQualityPart(param_json, PropertyConfigurer.parseStr("quality.apply.url"));
        if (jsResp.getIntValue("code") != 0) {
            logger.error("applyQualityTest ==> Invoke quality platform failed！url={},response={}", PropertyConfigurer.parseStr("quality.apply.url"), jsResp.toString());
            throw new QualityException(ErrorCodeMappingEnums.ERROR_HTTP_REQUEST_FAIL);
        }

        //修改状态:申请审核中
        qualityRecord.setStatus(ConstantDefine.QUALITY_STATUS_APPLY_VERIFY);

        //插入数据库
        return qualityRecordDao.insert(qualityRecord);
    }

    @Override
    public List<MdQualityRecord> queryQualityRecordList(Map<String, String> map) throws NORecordInDBException {
        //查询供应商是否存在
        MdVendor vendor = vendorDao.selectByPrimaryKey(Integer.valueOf(map.get("vendorId")));
        if (vendor == null) {
            logger.error("The vendor is not exist,vendorId=" + Integer.valueOf(map.get("vendorId")));
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_GOODS);
        }

        if (map.get("vendorGoodsId") != null) {
            //查询供应商水果是否存在
            MdVendorGoods vendorGoods = vendorGoodsDao.selectByPrimaryKey(Integer.valueOf(map.get("vendorGoodsId")));
            if (vendorGoods == null) {
                logger.error("The vendor's goods is not exist,vendorID=" + map.get("vendorId") + ",vendorGoodsId" + map.get("vendorGoodsId"));
                throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_GOODS);
            }
            if (!Objects.equals(vendorGoods.getGoodsId(), Integer.valueOf(map.get("goodsId")))) {
                logger.error("The goodsId is not match with vendorGoodsId!");
                throw new QualityException(ErrorCodeMappingEnums.ERROR_INVALID_GOODS);
            }
            if (!Objects.equals(vendorGoods.getVendorId(), Integer.valueOf(map.get("vendorId")))) {
                logger.error("The vendorId is incorrect!");
                throw new QualityException(ErrorCodeMappingEnums.ERROR_INVALID_VENDOR);
            }

        }

        //分页设置
        int pageNo = map.get("pageNo") == null ? 1 : Integer.parseInt(map.get("pageNo"));
        int pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize"));
        PageHelper.startPage(pageNo, pageSize, false);//开始分页,不统计总数

        return qualityRecordDao.queryQualityRecordList(map);
    }

    @Override
    public MdQualityRecord queryQualityRecordByID(int qualityRecordId) {
        return qualityRecordDao.queryQualityRecordByPrimaryKey(qualityRecordId);
    }

    @Override
    @Transactional
    public int updateQualityRecord(MdQualityRecord mdQualityRecord) {

        MdQualityRecord qualityRecord = qualityRecordDao.queryQualityRecordByPrimaryKey(mdQualityRecord.getQualityRecordId());
        //查询质检记录是否存在
        if (qualityRecord == null) {
            logger.error("The qualityRecord is not exist,mdQualityRecordID=" + mdQualityRecord.getQualityRecordId());
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
        }

        //调用远程接口参数
        Map<String, Object> param_json = new HashMap<String, Object>();
        param_json.put("code", mdQualityRecord.getQualityPlatId());
        param_json.put("express_company", mdQualityRecord.getExpressCompany());
        param_json.put("express_number", mdQualityRecord.getExpressNumber());
        param_json.put("expense_note", mdQualityRecord.getCostBelong());

        //调用质检平台接口:  提交送检
        JSONObject jsResp = InvokeQualityPartUtils.invokeQualityPart(param_json, PropertyConfigurer.parseStr("quality.delivery.url"));
        if (jsResp.getIntValue("code") != 0) {
            logger.error("updateQualityRecord ==> Invoke quality platform failed！url={},response={}", PropertyConfigurer.parseStr("quality.delivery.url"), jsResp.toString());
            throw new QualityException(ErrorCodeMappingEnums.ERROR_HTTP_REQUEST_FAIL);
        }

        return qualityRecordDao.updateByPrimaryKey(mdQualityRecord);
    }

    /**
     * 查询质检申请结果
     *
     * @param paramMap
     * @return
     */
    @Override
    @Transactional
    public void queryQualityApplyResult(Map<String, String> paramMap) {

        MdQualityRecord qualityRecord = qualityRecordDao.queryQualityRecordByPrimaryKey(Integer.valueOf(paramMap.get("qualityRecordId")));
        //查询质检记录是否存在
        if (qualityRecord == null) {
            logger.error("The qualityRecord is not exist,mdQualityRecordID=" + Integer.valueOf(paramMap.get("qualityRecordId")));
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
        }

        //查询供应商是否存在
        if (vendorDao.selectByPrimaryKey(Integer.valueOf(paramMap.get("vendorId"))) == null) {
            logger.error("The vendor is not exist,vendorID=" + Integer.valueOf(paramMap.get("vendorId")) + ",mdQualityRecordID=" + paramMap.get("qualityRecordId"));
            throw new NORecordInDBException(ErrorCodeMappingEnums.ERROR_INVALID_VENDOR);
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("code", paramMap.get("qualityPlatId"));

        //调用质检平台：查询质检结果
        JSONObject jsResp = InvokeQualityPartUtils.invokeQualityPart(map, PropertyConfigurer.parseStr("quality.apply.result.url"));
        if (jsResp.getIntValue("code") != 0) {
            logger.error("queryQualityApplyResult ==> Invoke quality platform failed！url={},response={}", PropertyConfigurer.parseStr("quality.apply.result.url"), jsResp.toString());
            throw new QualityException(ErrorCodeMappingEnums.ERROR_HTTP_REQUEST_FAIL);
        }

        JSONObject dataJson = jsResp.getJSONObject("data");

        //修改状态
        if (dataJson.getIntValue("reply_status") == 0) {
            logger.debug("No apply result,reply_status=" + dataJson.getIntValue("reply_status"));
            return;
        }
        String status = dataJson.getIntValue("reply_status") == 2 ? ConstantDefine.QUALITY_STATUS_APPlY_FAILED : ConstantDefine.QUALITY_STATUS_WAIT_TEST;

        qualityRecord.setStatus(status);
        int i = qualityRecordDao.updateByPrimaryKey(qualityRecord);
        if (i < 0) {
            logger.error("Failed to update quality record status! qualityRecordId={},status={}", Integer.valueOf(paramMap.get("qualityRecordId")), status);
            throw new QualityException(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        //插入反馈信息
        MdFeedback feedback = new MdFeedback();
        feedback.setQualityRecordId(Integer.valueOf(paramMap.get("qualityRecordId")));
        feedback.setQualityType(dataJson.getString("qc_type"));
        feedback.setTestOrgCode(dataJson.getString("delivery_center_code"));
        feedback.setTestOrgName(dataJson.getString("delivery_center_name"));
        feedback.setPrice((long) dataJson.getIntValue("offer_price"));
        feedback.setPhoneNumber(dataJson.getString("inspector_tel"));
        feedback.setTestUser(dataJson.getString("inspector"));
        feedback.setRemark(dataJson.getString("remark"));

        i = feedbackDao.insert(feedback);
        if (i < 0) {
            logger.error("Failed to insert MdFeedback! feedback=" + feedback.toString());
            throw new QualityException(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }
    }

}
